package kltn.audioguidetravel;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import kltn.business.BAInfoTravel;
import kltn.business.GPSTracker;
import kltn.business.Helper;
import kltn.business.InfoTravelAdapter;
import kltn.data.CopyDB;
import kltn.data.InfoTravel;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends ActionBarActivity {

	// Google Map
    private GoogleMap googleMap;
    // latitude and longitude
    private ArrayList<InfoTravel> infoTravels= new ArrayList<>();
    private ArrayList<InfoTravel> listInfoTravels= new ArrayList<>();
    private String linkData;
    private ListView lvInfo;
    private InfoTravelAdapter adapter;
    private GPSTracker gps;
    private double latitude;
    private double longitude;
    private BAInfoTravel baInfoTravel;
    
    private int startTime = 0;
    private int finalTime = 0;
    private SeekBar sbPlay;
    private MediaPlayer mediaPlayer;
	private ImageButton ibPlay;
	private TextView tvTime;
	private Handler myHandler = new Handler();;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new CopyDB().copy(getAssets());
		Intent intent= new Intent(this,WayActivity.class);
		startActivity(intent);
//		gps= new GPSTracker(this);
//		latitude=gps.getLatitude();
//		longitude=gps.getLongitude();
//		baInfoTravel= new BAInfoTravel(this);
//		infoTravels=baInfoTravel.getAllInfoTravel();
//		try {
//            ini();
//			loadInfo();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//		//Cập nhật DataBase
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				updateDataBase();
//				downloadDataBase();
//			}
//		}).start();
	}
	
	@SuppressLint("NewApi")
	public void loadInfo(){
		if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fMap)).getMap();
            for (InfoTravel i : infoTravels) {
            	double lati= i.getLatitude();
            	double longi=i.getLongitude();
				MarkerOptions marker= new MarkerOptions().position(new LatLng(lati,longi)).title(i.getName());
				marker.snippet(i.getLatitude()+";"+i.getLongitude());
				marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
				googleMap.addMarker(marker);
			}
            CameraPosition cameraPosition = new CameraPosition.Builder().target(
                    new LatLng(latitude, longitude)).zoom(12).build();
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);
            googleMap.setMyLocationEnabled(true);
            googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
				@Override
				public boolean onMarkerClick(Marker mar) {
					return false;
				}
			});
            googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
				@Override
				public void onCameraChange(CameraPosition camPos) {
					updateInfoTravel(camPos.target.latitude,camPos.target.longitude);
				}
			});
            googleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
				
				@Override
				public boolean onMyLocationButtonClick() {
					updateInfoTravel(gps.getLatitude(), gps.getLongitude());
					return false;
				}
			});
		}
	}
	public void updateInfoTravel(double latitude,double longitude){
		listInfoTravels.clear();
		listInfoTravels.addAll(baInfoTravel.getInfoTravelByLocaltion(new InfoTravel(latitude,longitude)));
		adapter.notifyDataSetChanged();
	}
	private Runnable UpdateSongTime = new Runnable() {
	      public void run() {
	         startTime = mediaPlayer.getCurrentPosition();
	         tvTime.setText(Helper.getMinutes(startTime)+"|"+Helper.getMinutes(finalTime));
	         sbPlay.setProgress(startTime);
	         myHandler.postDelayed(this, 100);
	      }
	   };
	private void play(String url) {
		ibPlay.setEnabled(true);
		sbPlay=(SeekBar) findViewById(R.id.sbPlayMain);
		sbPlay.setClickable(false);
		tvTime=(TextView) findViewById(R.id.tvTime);
		if (mediaPlayer==null)
			mediaPlayer = new MediaPlayer();
		else mediaPlayer.reset();
	    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	    try {
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepare(); // might take long! (for buffering, etc)
			finalTime = mediaPlayer.getDuration();
		    startTime = mediaPlayer.getCurrentPosition();
		    mediaPlayer.start();
		    ibPlay.setImageResource(android.R.drawable.ic_media_pause);
		    sbPlay.setMax(finalTime);
		    myHandler.postDelayed(UpdateSongTime,100);
		    tvTime.setText(Helper.getMinutes(startTime)+"|"+Helper.getMinutes(finalTime));
			
		} catch (IllegalArgumentException | SecurityException
				| IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    ibPlay.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					ibPlay.setImageResource(android.R.drawable.ic_media_play);
				}
				else{
					mediaPlayer.start();
					ibPlay.setImageResource(android.R.drawable.ic_media_pause);
				}
			}
		});
	}
	public void ini(){
		ibPlay=(ImageButton) findViewById(R.id.ibPlayMain);
		ibPlay.setEnabled(false);
		lvInfo=(ListView) findViewById(R.id.lvInfo);
		listInfoTravels=baInfoTravel.getInfoTravelByLocaltion(new InfoTravel(gps.getLatitude(), gps.getLongitude()));
		adapter = new InfoTravelAdapter(this,R.layout.item_info, listInfoTravels);
		lvInfo.setAdapter(adapter);
		lvInfo.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				play(listInfoTravels.get(pos).getAudio());
				CameraPosition cameraPosition = new CameraPosition.Builder().target(
	                    new LatLng(listInfoTravels.get(pos).getLatitude(),listInfoTravels.get(pos).getLongitude())).zoom(12).build();
	            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//				Intent intent= new Intent(MainActivity.this, DetailActivity.class);
//				intent.putExtra("urlAudio",listInfoTravels.get(pos).getAudio());
////				Log.d("test",infoTravels.get(pos).getAudio());
//				startActivity(intent);
			}
		});
	}
	
	public AlertDialog DialogUpdate()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Thông báo");
        String tbao="Có phiên bản mới bạn có muốn cập nhật?";
        builder.setMessage(tbao);
        builder.setNegativeButton("Có", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				new Thread(new Runnable() {
					@Override
					public void run() {
					}
				}).start();
			}
		});
        builder.setPositiveButton("Không", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        return dialog;
	}
	
	Handler handler = new Handler(new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 0){
				DialogUpdate().show();
			}else{
				new CopyDB().update(is);
			}
			return true;
		}
	});
	
    public void updateDataBase() {
    	String path ="https://dl.dropboxusercontent.com/s/xekf1jviq8i6rs4/Version.txt?dl=1&token_hash=AAEciwStbdgO5qUvExwS1quByd7mRP0MeisFZbGlso73aA";
		try {
			InputStream is = ((HttpURLConnection)(new URL(path))
					.openConnection()).getInputStream();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(is));
			
			if(!bufferedReader.readLine().equalsIgnoreCase(Helper.getVersion(this))){
				linkData=bufferedReader.readLine();
				handler.sendEmptyMessage(0);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
    InputStream is;
    public void downloadDataBase() {
		try {
			//linkData="https://dl.dropboxusercontent.com/s/x5uzy8jblgcf4m5/database.sqlite?dl=1&token_hash=AAGhpwHJOV-jWsZMbFfN6oRgtWTFckHZRITvGxMockYITw";
			linkData="https://dl.dropboxusercontent.com/s/dtz7qutx9cq9tvc/STGDataBase?dl=1&token_hash=AAH2ND3mXP42X39PPlfHpqy6HQuybT1xaSS3oN6gSKNakg";
			URL url = new URL(linkData);
			
			//Log.d("test",linkData);
			HttpURLConnection connection =(HttpURLConnection)url.openConnection();
			connection.connect();
			if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.d("test","Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());
            }
			long fileLength = connection.getContentLength();
			is = connection.getInputStream();
			
//			BufferedReader bufferedReader = new BufferedReader(
//					new InputStreamReader(is));
//			byte[] buffer =new byte[bufferedReader.read()];
			Log.d("test",fileLength+" byte buffer ");//+is.available());
//			handler.sendEmptyMessage(1);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			Log.d("test",e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			Log.d("test",e.getMessage());
		}
	}
}
